package com.irdstudio.efp.batch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.DateFormatConstant;
import com.irdstudio.basic.framework.core.constant.SDicToLocalConstant;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.util.sdic.SDicToLocal;
import com.irdstudio.cdp.pboc.service.facade.ZXHtmlInfoService;
import com.irdstudio.cdp.pboc.service.facade.ZXJsonInfoService;
import com.irdstudio.cdp.pboc.service.vo.PbocJobVO;
import com.irdstudio.cdp.pboc.service.vo.ZXJsonInfoVO;
import com.irdstudio.cdp.pboc.service.vo.ZxhtmlInfoOccVO;
import com.irdstudio.efp.batch.service.domain.CrrInfJsonArry;
import com.irdstudio.efp.batch.service.facade.MSJysSupplyService;
import com.irdstudio.efp.console.service.facade.SDicService;
import com.irdstudio.efp.console.service.vo.SDicListVO;
import com.irdstudio.efp.console.service.vo.SDicVO;
import com.irdstudio.efp.cus.service.facade.CusIndivOccTempService;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivOccTempVo;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.esb.common.constant.nls.NlsCrrEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 马上九要素补充互金（一次性批次）
 */

@Service("mSJysSupplyService")
public class MSJysSupplyServiceImpl implements MSJysSupplyService, FrameworkService {


    private final static Logger logger = LoggerFactory.getLogger(MSJysSupplyServiceImpl.class);

    private final static String opttype = "STD_ZX_EMPLOYMET";

    private static SimpleDateFormat sdf = new SimpleDateFormat(DateFormatConstant.DATE_FORMAT);

    @Override
    public boolean updateIndivOcc() {

        boolean flag = true;

        //获取数据字段中的职业信息，用于转换
        Map<String, String> occMap = new HashMap<>();
        SDicListVO sDicListVO = new SDicListVO();
        sDicListVO.setOpttype(opttype);
        List<SDicListVO> list = sDicService.queryByopttype(sDicListVO);
        for (SDicVO vo : list.get(0).getsDicVOs()) {
            occMap.put(vo.getCnname(), vo.getEnname());//{国家机关、党群组织、企业、事业单位负责人,0}
        }
        // 判断循环次数
        CusIndivVO pageInfo = new CusIndivVO();
        pageInfo.setFstAppChannel("04");
        // 页数
        int page = 1;
        pageInfo.setSize(5000);
        int size = cusIndivService.queryCusCountByFstChannel(pageInfo);
        logger.info("【客户信息表】数据量：" + size);

        int loopCount = (size / pageInfo.getSize()) + 1;

        for (int i = 0; i < loopCount; i++) {
            logger.info("【客户信息表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize());
            //分页查新马上金融客户信息
            List<CusIndivVO> tempList = cusIndivService.queryCusCountByFstChannelByPage(pageInfo);
            for (CusIndivVO vo : tempList) {
                if (StringUtil.isStrNotEmpty(vo.getIndivOcc())) {
                    if (!"Y".equals(vo.getIndivOcc()) && !"Z".equals(vo.getIndivOcc())) {
                        continue;
                    }
                }
                try {
                    //如果历史职业内容是“不便分类的其他从业人员”或者“未知”或者为空
                    ZXJsonInfoVO zXJsonInfoVO = new ZXJsonInfoVO();
                    String occ = null;
                    zXJsonInfoVO.setCertCode(vo.getCertCode());
                    zXJsonInfoVO.setCertType(vo.getCertType());
                    List<ZXJsonInfoVO> zxJsonInfoVOList = zxJsonInfoService.queryByCertCodeAndCertType(zXJsonInfoVO);
                    if (zxJsonInfoVOList != null && zxJsonInfoVOList.size() != 0) {
                        //二代征信查询到征信信息
                        for (ZXJsonInfoVO zxJsonInfoVO : zxJsonInfoVOList) {
                            if ((getDaysBetweenTwoDates(vo.getCreateTime(),TimeUtil.addDay(zxJsonInfoVO.getCreateTime(), 1)) == 1 ||
                                    getDaysBetweenTwoDates(vo.getCreateTime(),TimeUtil.addDay(zxJsonInfoVO.getCreateTime(), 1)) == 0 ) &&
                                    StringUtil.isNotEmpty(zxJsonInfoVO.getJsonContent())) {
                                //获取人行征信表中的征信json报告内容
                                String content = zxJsonInfoVO.getJsonContent();
                                //获取征信json报告内容中最新的职业字段
                                occ = parseOcc(content);
                                insertCusIndiv(vo, occ);
                            }
                        }
                    }
                    if (zxJsonInfoVOList == null || zxJsonInfoVOList.size() == 0 || StringUtil.isNullorBank(occ)) {
                        //如果二代人行征信不存在数据，则查询一代征信表
                        ZxhtmlInfoOccVO zxhtmlInfoOccVO = new ZxhtmlInfoOccVO();
                        zxhtmlInfoOccVO.setCertcode(vo.getCertCode());
                        //根据客户证件类型、证件号码查询一代人行征信表
                        List<ZxhtmlInfoOccVO> ZxhtmlInfoOccList = zxHtmlInfoService.queryListBycerCode(zxhtmlInfoOccVO);
                        if (ZxhtmlInfoOccList != null && ZxhtmlInfoOccList.size() > 0) {
                            for (ZxhtmlInfoOccVO reportVO : ZxhtmlInfoOccList) {
                                if (getDaysBetweenTwoDates(vo.getCreateTime(),TimeUtil.addDay(reportVO.getCreateTime(), 1)) == 1 ||
                                        getDaysBetweenTwoDates(vo.getCreateTime(),TimeUtil.addDay(reportVO.getCreateTime(), 1)) ==  0) {
                                    occ = transOcc(reportVO.getPbocJobVOS(), occMap);
                                    insertCusIndiv(vo, occ);
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                    logger.error("根据人行征信信息更新客户表失败!!!", e);
                    flag = false;
                }

            }
            pageInfo.setPage(++page);
        }


        return flag;
    }

    private void insertCusIndiv(CusIndivVO vo, String occ) {
        if (StringUtil.isNotEmpty(occ)) {
            CusIndivVO updCusIndivVO = new CusIndivVO();
            updCusIndivVO.setCusId(vo.getCusId());
            updCusIndivVO.setIndivOcc(occ);
            updCusIndivVO.setLastUpdateUser("admin_rhzx");//将更新成功的客户信息的最后更新人设置为“admin_rhzx”，用于后期统计
            updCusIndivVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());//更新
            //更新客户表
            cusIndivService.updateByPk(updCusIndivVO);
            //更新客户表的临时表
            CusIndivOccTempVo cusIndivOccTempVo = new CusIndivOccTempVo();
            cusIndivOccTempVo.setCusId(vo.getCusId());
            cusIndivOccTempVo.setIndivOccRepair(occ);
            cusIndivOccTempVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
            cusIndivOccTempVo.setFlag("1");
            cusIndivOccTempService.updateByPk(cusIndivOccTempVo);
        }
    }

    /**
     * 获取征信json报告内容中最新的职业信息字段
     *
     * @param content
     * @return
     * @throws Exception
     */
    private String parseOcc(String content) throws Exception {
        String crrInfo = null;
        JSONObject jsonObj = JSONObject.parseObject(content);
        JSONArray result = jsonObj.getJSONArray("CrrInfArry");
        List<CrrInfJsonArry> list;
        if (result != null) {
            list = JSON.parseArray(result.toJSONString(), CrrInfJsonArry.class);
            if (list != null && list.size() > 0) {
                Collections.sort(list);
                for (CrrInfJsonArry crrInfJsonArry : list) {
                    if (!StringUtil.isNullorBank(crrInfJsonArry.getCrrCd()) && !NlsCrrEnum.OTHER.getValue().
                            equals(crrInfJsonArry.getCrrCd()) && !NlsCrrEnum.UNKNOWN.getValue().equals(crrInfJsonArry.getCrrCd())) {
                        crrInfo = SDicToLocal.getLocalSysDicVal(SDicToLocalConstant.CRR, crrInfJsonArry.getCrrCd());
                        break;
                    }
                }
            }
        }
        return crrInfo;
    }

    /**
     * 将一代征信中的职业字段转为行业标准
     *
     * @param list
     * @param map
     * @return
     */
    private String transOcc(List<PbocJobVO> list, Map<String, String> map) {
        String crrInfo = null;
        if (list != null && list.size() > 0) {
            for (PbocJobVO pbocJobVO : list) {
                if (StringUtil.isNotEmpty(map.get(pbocJobVO.getProfession())) && !"Y".equals(map.get(pbocJobVO.getProfession()))
                        && !"Z".equals(map.get(pbocJobVO.getProfession()))) {
                    crrInfo = map.get(pbocJobVO.getProfession());
                    break;
                }
            }
        }

        return crrInfo;
    }

    public static int getDaysBetweenTwoDates(String date1, String date2) throws Exception {
        int result;
        try {
            long d1 = sdf.parse(date1).getTime();
            long d2 = sdf.parse(date2).getTime();

            result = (int) ((d2 - d1) / 1000 / 60 / 60 / 24);
        } catch (ParseException e) {
            throw new Exception(e);
        }
        return result;
    }

    @Resource
    @Qualifier("zxJsonInfoService")
    private ZXJsonInfoService zxJsonInfoService;

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("sDicService")
    private SDicService sDicService;

    @Autowired
    @Qualifier("zxHtmlInfoService")
    private ZXHtmlInfoService zxHtmlInfoService;

    @Autowired
    @Qualifier("cusIndivOccTempService")
    private CusIndivOccTempService cusIndivOccTempService;
}
